package com.ljq.order.controller;

import com.alibaba.fastjson.JSON;
import com.ljq.entity.Order;
import com.ljq.entity.Product;
import com.ljq.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.Map;

/**
 * @Author 罗集强
 * @Date 2022/5/13 19:35
 */
@RestController
@Slf4j
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderService orderService; //准备买1件商品


    @Autowired private DiscoveryClient discoveryClient;

    @GetMapping("/order/prod/{pid}")
    public Order order(@PathVariable("pid") Integer pid) {
        log.info(">>客户下单，这时候要调用商品微服务查询商品信息");
        //通过restTemplate调用商品微服务
        Product product = restTemplate.getForObject("http://localhost:8081/product/" + pid, Product.class);
        Order order = new Order();
        order.setUid(1);
        order.setPid(product.getPid());
        order.setUsername("张三");
        return orderService.save(order);
    }

    @GetMapping("/order/prod/nacos/{pid}")
    public Order orderByNacos(@PathVariable("pid") Integer pid) {
        log.info(">>客户下单，这时候要调用商品微服务查询商品信息");
        //从nacos中获取服务地址
        ServiceInstance serviceInstance = discoveryClient.getInstances("shop-product").get(0);
        String url = serviceInstance.getHost() + ":" +serviceInstance.getPort();

        /**
         *  尝试拿到服务的配置信息，注册到nacos的注册源信息
         */

        Map<String, String> metadata = serviceInstance.getMetadata();
        Iterator<Map.Entry<String, String>> iterator = metadata.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
           log.error("key: "+key+"===》value: "+value);
        }
        log.info(">>从nacos中获取到的微服务地址为:" + url);
        //通过restTemplate调用商品微服务
        Product product = restTemplate.getForObject( "http://" + url + "/product/" + pid, Product.class);
        log.info(">>商品信息,查询结果:" + JSON.toJSONString(product));
        Order order = new Order();
        order.setUid(1);
        order.setUsername("测试用户");
        order.setPid(product.getPid());
        return orderService.save(order);
    }
}